import voronin.ConnectionPoolService;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SocketConsumer extends Thread {
    private List<Socket> connections = new ArrayList<>();
    private ConnectionPoolService<Socket> service;

    public SocketConsumer(ConnectionPoolService<Socket> service) {
        this.service = service;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            Socket socket = service.tryGet();
            if (socket != null) {
                connections.add(socket);
            }
        }
        try {
            synchronized (this){
                wait();
            }
        } catch (InterruptedException e) {
            Socket socket = connections.remove(0);
            if (socket != null) {
                service.release(socket);
            }
        }
        try {
            synchronized (this) {
                wait();
            }
        } catch (InterruptedException e) {
            while (connections.size() > 0) {
                service.release(connections.remove(0));
            }
        }
    }
}
